var nimo_w2utils = (function () {
    var obj = {
        version  : '0.0.1',
        grid2csv        : grid2csv,
        gridSummary     : gridSummary,
        gridPrint       : gridPrint,
        dummy           : null
    };
    return obj;

    function gridSummary(grid, setting) {
        console.log(grid.summary);
        if ( grid.summary.length>0 ) {
            for (var c = 0; c < grid.columns.length; c++) {
                var sum = 0;
                for (var r = 0; r < grid.records.length; r++) {
                    var val = grid.getCellValue(r, c);
                    if (val === parseInt(val, 10)) {
                        sum = sum + val;
                    }
                }
                if (sum!=0) {
                    grid.summary[0][grid.columns[c].field] = sum;
                    grid.summary[1][grid.columns[c].field] = parseInt(sum/grid.records.length);
                }
            }
            grid.refresh(grid.summary[0].recid);
            grid.refresh(grid.summary[1].recid);
        }
    }

    function gridPrint(grid, setting) {
        $('#'+grid.box.id).printThis();
    }

    function grid2csv (grid, setting) {
        var date = new Date();
        var option = $.extend({filename:grid.name + '' + date.getFullYear() + ('0' + date.getMonth() + 1).slice(-2) + ('0' + date.getDate()).slice(-2) + '.csv'}, setting);
        var csv = '';
        var columns = [];
        for (var i = 0; i < grid.columns.length; i++) { if (!grid.columns[i].hidden) columns.push(grid.columns[i]);}
        columns.forEach(function (e, i) { csv += e.caption + ',';});
        csv +='\n';
        for (var r = 0; r < grid.records.length; r++) {
          var rec = grid.records[r];
          for (var i = 0; i < columns.length; i++) {
            var val= rec[columns[i].field];
            val = (val!=null&&val!==undefined&&(typeof val==='string'||!isNaN(val)))?val : '';
            csv += val + ',';
          }
          csv +='\n';
        }
        var a   = document.createElement('a');
        a.href  = 'data:attachment/csv,\uFEFF' +  encodeURIComponent(csv);
        a.target      = '_blank';
        a.download    = option.filename;
        document.body.appendChild(a);
        a.click();
        a.remove();
    }
})();
